<template>
	<d2-container>
		<!-- 搜索 -->
		<template slot="header">
			<el-form ref="indexForm" class="header-area" :model="indexForm" label-width="100px" style="height: auto">
				<el-row>
					<el-col :span="6">
						<el-form-item label="商品名称" prop="productName">
							<el-input type="text" v-model="indexForm.productName" placeholder="请输入商品名称"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="商品品牌" prop="brandId">
							<el-cascader v-model="brandIds" :options="brandTree"
								:props="{ value: 'id', label: 'brandName' }" @change="handleChangeBrand"
								placeholder="请选择品牌" style="width: 100%;"></el-cascader>
						</el-form-item>
					</el-col>
					<el-col :span="7">
						<el-form-item label="商品分类" prop="thirdLevelId">
							<el-cascader
								v-model="categoryIds"
								:options="categoryTree"
								:props="{ value: 'id', label: 'categoryName' }"
								@change="handleChangeCategory"
								placeholder="请选择分类" style="width: 100%;"
							></el-cascader>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="6">
						<el-form-item label="商品编码" prop="productCode">
							<el-input type="text" v-model="indexForm.productCode" placeholder="请输入商品编码"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="状态" prop="status">
							<el-select v-model="indexForm.status" placeholder="请选择状态" style="width: 100%;">
								<el-option label="全部" value=""></el-option>
								<el-option label="上架" value="1"></el-option>
								<el-option label="下架" value="0"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="7">
						<el-form-item label="创建时间" prop="time">
							<el-date-picker
								v-model="time"
								type="datetimerange"
								range-separator="至"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								value-format="timestamp" align="right"
								style="width: 100%"
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<div class="search-submit">
							<el-button type="primary" size="medium" @click="submitForm('indexForm')">查询</el-button>
							<el-button size="medium" @click="resetForm('indexForm')">重置</el-button>
						</div>
					</el-col>
				</el-row>
			</el-form>
		</template>

		<!-- 列表 -->
		<template>
			<div class="table-header">
				<el-button type="primary" @click="add">新 增</el-button>
				<el-button @click="copy">一键复制</el-button>
			</div>

			<el-table :data="tableData" stripe border style="width: 100%" @selection-change="handleSelectionChange">
				<el-table-column type="selection" align="center" width="50"></el-table-column>
				
				<el-table-column label="商品缩略图" width="101">
					<template slot-scope="scope">
						<el-image fit="cover" :src="scope.row.thumbImage" :preview-src-list="[scope.row.thumbImage]" style="width: 80px; height: 80px;"></el-image>
					</template>
				</el-table-column>
				
				<el-table-column prop="productCode" label="商品编码" width="120"></el-table-column>
				<el-table-column prop="productName" label="商品名称"></el-table-column>
				<el-table-column prop="brandName" label="品牌" width="150"></el-table-column>
				<el-table-column label="分类" width="120">
					<template slot-scope="scope">
						{{scope.row.firstLevelName}} - <br>
						{{scope.row.secondLevelName}} - <br>
						{{scope.row.thirdLevelName}}
					</template>
				</el-table-column>
				
				<el-table-column prop="status" label="状态" width="100" align="center">
					<template slot-scope="scope">
						<el-tag :type="scope.row.status === 1 ? 'success' : 'warning'" disable-transitions>{{ scope.row.status == 0 ? '下架' : '上架' }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column align="center" label="查看SKU" width="140">
					<template slot-scope="scope">
						<div>
							<el-button type="primary" plain size="small" @click="skuRow(scope.row)">sku上下架</el-button>
						</div>
						<div style="margin-top: 10px;">
							<el-button type="primary" plain size="small" @click="skuUpdateRow(scope.row)">sku改名</el-button>
						</div>
					</template>
				</el-table-column>
				
				<el-table-column prop="createTime" label="创建时间" :formatter="forDateCreate" width="100"></el-table-column>
				<el-table-column prop="reviseTime" label="修改时间" :formatter="forDateRevise" width="100"></el-table-column>
				
				<el-table-column align="center" fixed="right" label="操作" width="280">
					<template slot-scope="scope">
						<el-button type="success" size="small" @click="showRow(scope.row.id)">查看</el-button>
						<el-button type="primary" size="small" @click="updateRow(scope.row.id)">编辑</el-button>
						<el-button type="danger" v-if="scope.row.status == 0" size="small" @click.native.prevent="operateStatus(scope.$index, scope.row, 1)">上架</el-button>
						<el-button type="danger" v-if="scope.row.status == 1" size="small" @click.native.prevent="operateStatus(scope.$index, scope.row, 0)">下架</el-button>
						<el-button type="info" size="small" @click.native.prevent="deleteRow(scope.$index, scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</template>

		<!-- 翻页 -->
		<template slot="footer">
			<div class="page">
				<el-pagination
					background
					layout="total, sizes, prev, pager, next, jumper"
					:page-sizes="[10, 20, 50, 100]"
					:current-page="currentPage"
					:page-size="pageSize"
					:total="total"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				></el-pagination>
			</div>
		</template>

		<!-- 弹窗 -->
		<template>
			<!-- 商品sku弹窗(上下架) -->
			<el-dialog :title="skuDialogTitle" :visible.sync="dialogSkuVisible" width="85%">
				<!-- 商品SKU表格 -->
				<div>
					<el-table :data="skuTableData" border style="width: 100%;">
						<el-table-column type="selection" align="center" width="50"></el-table-column>
						
						<el-table-column prop="thumbImage" label="图片" width="100" align="center">
							<template slot-scope="scope">
								<el-image :src="scope.row.thumbImage" style="width: 60px; height: 60px;"></el-image>
							</template>
						</el-table-column>
						
						<el-table-column prop="skuName" label="SKU名称" align="center"></el-table-column>
						<el-table-column prop="productSkuCode" label="SKU编码" align="center"></el-table-column>
						<el-table-column prop="productBarCode" label="条码" width="150" align="center"></el-table-column>
						
						<el-table-column prop="pricePurchase" label="参考进货价(元)" width="100"
							align="center"></el-table-column>
						<el-table-column prop="priceShow" label="原价(元)" width="100" align="center"></el-table-column>
						<el-table-column prop="price" label="销售价(元)" width="100" align="center"></el-table-column>
						<el-table-column prop="memberPrice" label="会员价(元)" width="100" align="center"></el-table-column>
						<el-table-column prop="couponAmount" label="券抵扣金额(元)" width="100" align="center"></el-table-column>
						<el-table-column prop="stockTotal" label="总库存" width="110" align="center"></el-table-column>
						
						<el-table-column prop="status" label="状态" width="100" align="center">
							<template slot-scope="scope">
								<el-tag :ref="'statusTag' + scope.$index">{{ scope.row.status == 1 ? '上架' : '下架' }}</el-tag>
							</template>
						</el-table-column>
						<el-table-column prop="operate" label="操作" width="100" align="center">
							<template slot-scope="scope">
								<el-button type="success" v-if="scope.row.status == 0" size="small" @click.native.prevent="operateSkuStatus(scope.$index, scope.row, 1)">
									上架
								</el-button>
								<el-button type="success" v-if="scope.row.status == 1" size="small" @click.native.prevent="operateSkuStatus(scope.$index, scope.row, 0)">
									下架
								</el-button>
							</template>
						</el-table-column>
					</el-table>
				</div>
				<div slot="footer" class="dialog-footer"><el-button @click="dialogSkuClose">关 闭</el-button></div>
			</el-dialog>
			
			<!-- 商品sku弹窗(改名)) -->
			<el-dialog :title="updateSkuDialogTitle" :visible.sync="dialogUpdateSkuVisible" width="75%">
				<!-- 商品SKU表格 -->
				<div>
					<el-table :data="updateSkuTableData" border style="width: 100%;">
						<el-table-column type="selection" align="center" width="50"></el-table-column>
						
						<el-table-column prop="thumbImage" label="图片" width="100" align="center">
							<template slot-scope="scope">
								<el-image :src="scope.row[scope.column.property]" style="width: 60px; height: 60px;"></el-image>
							</template>
						</el-table-column>
						
						<el-table-column prop="skuName" label="SKU名称" align="center"></el-table-column>
						<el-table-column prop="productSkuCode" label="SKU编码" align="center"></el-table-column>
						
						<el-table-column prop="propertyNames" label="规格名称组合" align="center"></el-table-column>
						<el-table-column prop="originalPropertyValueNames" label="原始规格值名称组合" align="center"></el-table-column>
						<el-table-column prop="propertyValueNames" label="规格值名称组合" align="center">
							<template slot-scope="scope">
								<el-input v-model="scope.row[scope.column.property]" placeholder="请输入"></el-input>
							</template>
						</el-table-column>
						<el-table-column prop="productBarCode" label="条码" width="100" align="center"></el-table-column>
						
						<el-table-column prop="pricePurchase" label="参考进货价(元)" width="100" align="center"></el-table-column>
						<el-table-column prop="priceShow" label="原价(元)" width="100" align="center"></el-table-column>
						<el-table-column prop="price" label="销售价(元)" width="100" align="center"></el-table-column>
						<el-table-column prop="memberPrice" label="会员价(元)" width="100" align="center"></el-table-column>
						<el-table-column prop="couponAmount" label="券抵扣金额(元)" width="100" align="center"></el-table-column>
						
						<el-table-column prop="operate" label="操作" width="120" align="center">
							<template slot-scope="scope">
								<el-button type="success" size="small" @click.native.prevent="updateSkuPropertyValueNames(scope.$index, scope.row)">确认修改</el-button>
							</template>
						</el-table-column>
					</el-table>
				</div>
				<div slot="footer" class="dialog-footer"><el-button @click="dialogUpdateSkuClose">关 闭</el-button></div>
			</el-dialog>
		</template>
	</d2-container>
</template>
<script>
	import { ossDomain } from '@api/sys.common'
	import { findProductInfoListByPage, del, operateStatus, copy } from '@api/product/product'
	import { findProductSkuList, operateSkuStatus, updateSkuPropertyValueNames } from '@api/product/productSku'
	import { findBrandTree } from '@api/product/productBrand'
	import { findCategoryTree } from '@api/product/productCategory'
	import { findProductSkuStock } from '@api/stock/stock'
	import dayjs from 'dayjs'
	export default {
		name: 'productInfoSku-index',
		components: {},
		data() {
			return {
				indexForm: {
					productName: '',
					productCode: '',
					status: '',
					brandId: '',
					thirdLevelId: '',
					startTime: '',
					endTime: ''
				},
				brandIds: [],
				brandTree: [],
				categoryIds: [],
				categoryTree: [],
				time: [],
				tableData: [],
				currentPage: 1,
				pageSize: 10,
				total: 0,
				multipleSelection: [],
				// 查看商品SKU
				productId: '',
				skuDialogTitle: '',
				dialogSkuVisible: false,
				skuTableData: [],
				skuTableDataSpan: [],
				headerDatas: [],
				// 更改商品SKU
				updateProductId: '',
				updateSkuDialogTitle: '',
				dialogUpdateSkuVisible: false,
				updateSkuTableData: [],

				imgUrlHeader: '' // 图片地址
			}
		},
		methods: {
			fetchData() {
				this.loading = true;
				
				this.getBrandList();
				this.getCategoryList();
				this.indexForm.startTime = this.time[0];
				this.indexForm.endTime = this.time[1];
				
				findProductInfoListByPage({
					productName: this.indexForm.productName,
					productCode: this.indexForm.productCode,
					status: this.indexForm.status,
					brandId: this.indexForm.brandId,
					thirdLevelId: this.indexForm.thirdLevelId,
					startTime: this.indexForm.startTime,
					endTime: this.indexForm.endTime,
					currentPage: this.currentPage,
					pageSize: this.pageSize
				})
					.then(res => {
						this.tableData = res.data.content;
						this.total = res.data.total;
						this.loading = false;
					})
					.catch(err => {
						console.log('err', err);
						this.loading = false;
					})
			},
			handleSizeChange(val) {
				this.pageSize = val;
				this.fetchData();
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.fetchData();
			},
			operateStatus(index, row, status) {
				this.$confirm('确认' + (status == 1 ? '上架' : '下架') + row.productName + '？')
					.then(_ => {
						this.loading = true;
						operateStatus({
								id: row.id,
								status: status
							})
							.then(res => {
								var code = res.code;
								if (code == '000000') {
									this.$message({
										message: res.message,
										type: 'success'
									});
									this.fetchData();
									this.loading = false;
								} else {
									this.$message({
										message: res.message,
										type: 'error'
									});
								}
							})
							.catch(err => {
								console.log('err', err);
								this.loading = false;
							})
					})
			},
			deleteRow(index, row) {
				this.$confirm('确认删除' + row.productName + '？')
					.then(_ => {
						this.loading = true;
						del({ id: row.id })
							.then(res => {
								var code = res.code;
								if (res.code == '000000') {
									this.$message({
										message: res.message,
										type: 'success'
									});
									this.fetchData();
									this.loading = false;
								} else {
									this.$message({
										message: res.message,
										type: 'error'
									});
								}
							})
							.catch(err => {
								console.log('err', err);
								this.loading = false;
							})
					})
			},
			forDateCreate(row, column) {
				return row.createTime == null ? '' : dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss');
			},
			forDateRevise(row, column) {
				return row.reviseTime == null ? '' : dayjs(row.reviseTime).format('YYYY-MM-DD HH:mm:ss');
			},
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			resetPage() {
				(this.currentPage = 1), (this.pageSize = 10), (this.total = 0);
			},
			submitForm(formName) {
				this.resetPage();
				this.fetchData();
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
				this.brandIds = [];
				this.categoryIds = [];
				this.time = [];
				
				this.resetPage();
				this.fetchData();
			},
			getBrandList() {
				findBrandTree({
					parentId: 0
				})
					.then(res => {
						// 调用递归方法，去除级联数据后将数据赋值给级联选择器
						this.brandTree = this.getTreeData(res.data);
					})
					.catch(err => {
						console.log('err', err);
						this.loading = false;
					})
			},
			handleChangeBrand(value) {
				var ids = (this.brandIds = value);
				this.indexForm.brandId = ids[ids.length - 1];
			},
			getCategoryList() {
				findCategoryTree()
					.then(res => {
						// 调用递归方法，去除级联数据后将数据赋值给级联选择器
						this.categoryTree = this.getTreeData(res.data);
					})
					.catch(err => {
						console.log('err', err);
						this.loading = false;
					})
			},
			handleChangeCategory(value) {
				var ids = (this.categoryIds = value);
				this.indexForm.thirdLevelId = ids[ids.length - 1];
			},
			// 递归方法
			getTreeData(data) {
				for (var i = 0; i < data.length; i++) {
					if (data[i].children == 'null' || data[i].children.length < 1) {
						// children若为空数组，则将children设为undefined
						data[i].children = undefined;
					} else {
						// children若不为空数组，则继续 递归调用 本方法
						this.getTreeData(data[i].children);
					}
				}
				return data;
			},
			// 新增
			add() {
				this.$router.push('/product/productInfoSku/add');
			},
			// 编辑
			updateRow(id) {
				sessionStorage.setItem('productId', id);
				this.$router.push('/product/productInfoSku/update');
			},
			// 查看
			showRow(id) {
				sessionStorage.setItem('productId', id);
				this.$router.push('/product/productInfoSku/details');
			},
			// 一键复制
			copy() {
				if (this.multipleSelection.length == 0) {
					this.$message.warning('请先选择要复制的商品');
					return false;
				}
				if (this.multipleSelection.length > 1) {
					this.$message.warning('只允许复制单个商品');
					return false;
				}
				
				let row = this.multipleSelection[0];
				this.$confirm('确认复制' + row.productName + '？')
					.then(_ => {
						this.loading = true;
						
						copy({ id: row.id })
							.then(res => {
								if (res.code == '000000') {
									this.$message({
										message: res.message,
										type: 'success'
									});
									this.fetchData();
									this.loading = false;
								} else {
									this.$message({
										message: res.message,
										type: 'error'
									});
								}
							})
							.catch(err => {
								console.log('err', err);
								this.loading = false;
							})
					})
			},
			// sku上下架弹窗
			skuRow(row) {
				this.dialogSkuVisible = true;
				this.productId = row.id;
				this.skuDialogTitle = '商品【' + row.productName + '】SKU列表';
				this.findSku(this.productId);
			},
			dialogSkuClose() {
				this.dialogSkuVisible = false;
			},
			findSku(productId) {
				this.skuTableData = [];
				findProductSkuList({
					productId: productId
				})
					.then(res => {
						for (let i = 0; i < res.data.length; i++) {
							let sku = res.data[i];

							// 查询商品SKU库存
							findProductSkuStock({
								skuId: sku.id
							})
								.then(res => {
									this.$set(sku, "stockTotal", res.data == undefined ? 0 : res.data.stockTotal);
								})
								.catch(err => {
									console.log('err', err);
									this.loading = false;
								})

							this.skuTableData.push(sku);
						}

					})
					.catch(err => {
						console.log('err', err);
						this.loading = false;
					})
			},
			// sku上下架
			operateSkuStatus(index, row, status) {
				this.$confirm('确认' + (status == 0 ? '上架' : '下架') + '【' + row.skuName + '】？')
					.then(_ => {
						this.loading = true;
						operateSkuStatus({
								skuId: row.id,
								status: status
							})
							.then(res => {
								if (res.code == '000000') {
									this.$message({
										message: res.message,
										type: 'success'
									});
									this.findSku(this.productId);
									this.loading = false;
								} else {
									this.$message({
										message: res.message,
										type: 'error'
									});
								}
							})
							.catch(err => {
								console.log('err', err);
								this.loading = false;
							})
					})
			},
			// sku改名弹窗
			skuUpdateRow(row) {
				this.dialogUpdateSkuVisible = true;
				this.updateProductId = row.id;
				this.updateSkuDialogTitle = '商品【' + row.productName + '】SKU列表';
				this.findUpdateSku(this.updateProductId);
			},
			dialogUpdateSkuClose() {
				this.dialogUpdateSkuVisible = false;
			},
			findUpdateSku(productId) {
				findProductSkuList({
					productId: productId
				})
					.then(res => {
						// 赋值商品SKU
						this.updateSkuTableData = res.data;
					})
					.catch(err => {
						console.log('err', err);
						this.loading = false;
					})
			},
			// sku改名规格值名称组合
			updateSkuPropertyValueNames(index, row) {
				if (row.propertyValueNames == '' || row.propertyValueNames == undefined) {
					this.$message.warning('规格值名称组合不允许为空');
					return false;
				}
				if (row.originalPropertyValueNames.indexOf(',') != -1 && row.propertyValueNames.indexOf(',') == -1) {
					this.$message.warning('规格值名称组合格式不正确');
					return false;
				}
				let num = 0
				for (let i = 0; i < row.propertyValueNames.length; i++) {
					if (row.propertyValueNames[i] == ',') {
						num++;
					}
				}
				if (num > 1) {
					this.$message.warning('规格值名称组合格式不正确');
					return false;
				}
				
				this.$confirm('确认修改规格值名称组合？')
					.then(_ => {
						this.loading = true;
						
						updateSkuPropertyValueNames({
							skuId: row.id,
							propertyValueNames: row.propertyValueNames
						})
							.then(res => {
								if (res.code == '000000') {
									this.$message({
										message: res.message,
										type: 'success'
									});
									this.loading = false;
								} else {
									this.$message({
										message: res.message,
										type: 'error'
									});
								}
							})
							.catch(err => {
								console.log('err', err);
								this.loading = false;
							})
					})
			}
		},
		mounted() {
			this.fetchData();
			this.imgUrlHeader = ossDomain;
		},
	}
</script>